import type { FormInstance } from "element-plus"
import { addUserData, editUserData } from "@@/apis/users/index"
import {
  ElMessage

} from "element-plus"
// useForm.ts
import { ref } from "vue"

export function useForm(refreshData: () => void) {
  const getDefaultFormData = () => {
    return {
      username: "",
      role: "user",
      remark: ""
    }
  }

  const formData = ref(getDefaultFormData())

  const formDataRef = ref()
  const formRules = {
    username: [{ required: true, message: "请输入用户名", trigger: "blur" }]
  }

  const addDialogVisible = ref(false)

  const isEdit = ref(false)
  const showDialog = () => {
    addDialogVisible.value = true
  }

  const resetData = () => {
    formData.value = getDefaultFormData()
    if (formDataRef.value) {
      formDataRef.value.resetFields()
    }
    isEdit.value = false
  }

  const closeDialog = () => {
    addDialogVisible.value = false
    resetData()
  }
  const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        try {
          if (isEdit.value) {
            await editUserData(formData.value)
          } else {
            await addUserData(formData.value)
          }
          ElMessage.success("操作成功")
          closeDialog()
          refreshData() // 刷新列表
        } catch (error) {
          const mes = error instanceof Error ? error.message : String(error) || "添加失败"
          console.error(mes)
        }
      } else {
        console.log("error submit!", fields)
      }
    })
  }

  return {
    formData,
    formRules,
    formDataRef,
    addDialogVisible,
    isEdit,
    showDialog,
    closeDialog,
    submitForm
  }
}
